package com.rednose.videoplayer.activities;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.rednose.videoplayer.R;
import com.rednose.videoplayer.controller.*;
import com.rednose.videoplayer.utils.Utility;
public class LoginActivity extends AppCompatActivity {

    private EditText usernameEditText;
    private EditText passwordEditText;
    private Button loginButton,toRegisterButton;

    private LoginController loginController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        toRegisterButton = findViewById(R.id.toRegisterButton);

        //用sharedPreferences检查是否已经登录，如果已经登录就跳转MainActivity
        SharedPreferences preferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String value = preferences.getString("isLogged","");
        if (value.equals("OK")) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }



        loginController = new LoginController(this);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                String passwordHash = Utility.hashPassword(password); // 哈希密码

                if (loginController.login(username, passwordHash)) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    // 用sharedPreferences保存登录状态
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("isLogged","OK");
                    editor.putString("username",username);
                    editor.apply();

                    // 跳转到下一个活动也就是主界面
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
        toRegisterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }


}
